package com.mengshu.mybatisplus.basic;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mengshu.mybatisplus.validator.ValidatorGroup;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.constraints.NotNull;
import java.util.List;

public class BasicController<S extends BasicService<T>, T extends BasicPO> {

    @Autowired
    private S service;

    @PostMapping("list")
    public List<T> list(@RequestBody T search) {
        return service.list(new LambdaQueryWrapper<T>()
                .orderByAsc(T::getId)
                .setEntity(search));
    }

    @PostMapping("page/{page}/{limit}")
    public IPage<T> page(@RequestBody T search, @PathVariable Integer page, @PathVariable Integer limit) {
        return service.page(new Page<>(page, limit), new LambdaQueryWrapper<T>()
                .orderByAsc(T::getId)
                .setEntity(search));
    }

    @PostMapping("info")
    public T info(@RequestBody @Validated IdReq req) {
        return service.getById(req.getId());
    }

    @PostMapping("save")
    public boolean save(@RequestBody @Validated(ValidatorGroup.Save.class) T t) {
        return service.saveForUniqueKey(t);
    }

    @PostMapping("update")
    public boolean update(@RequestBody @Validated(ValidatorGroup.Update.class) T t) {
        return service.updateForUniqueKey(t);
    }

    @PostMapping("delete")
    public void delete(@RequestBody @Validated IdReq req) {
        service.removeById(req.getId());
    }

    protected S getBasicService() {
        return service;
    }

    @Data
    public static class IdReq {
        @NotNull(message = "ID不能为空")
        private Long id;
    }
}
